package org.java.documents.jdk.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;

@Configuration
@EnableResourceServer
//@EnableWebSecurity()
@EnableGlobalMethodSecurity(
//       方法的安全拦截是基于AOP方式实现的，prePost表示在调用方法之前进行权限判断
        prePostEnabled=true,
        //spring提供的安全注解
        securedEnabled=true,
//        JSR 250是由Java官方提供的安全注解
        jsr250Enabled=true,
        proxyTargetClass=true)
public class ResourceServiceConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //让所有人都可以访问的路径
        http.authorizeRequests()
                //除了这里面的，其它都需要授权才能访问
                .antMatchers("/actuator/**").permitAll()
                .anyRequest().authenticated();
    }
    @Bean
    JwtTokenStore tokenStore() {
        return new JwtTokenStore(tokenConverter());
    }
    @Bean
    JwtAccessTokenConverter tokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();

        // ClassPathResource用于读取类路径下面的资源文件
        // "123456"是生成【密钥库】的时候提供的密码，-storepass参数的值
        KeyStoreKeyFactory keyStoreKeyFactory
                = new KeyStoreKeyFactory(new ClassPathResource("test.jks"),
                "123456".toCharArray());
        // 123456 是-keypass的值
        KeyPair keyPair = keyStoreKeyFactory
                .getKeyPair("test");

        converter.setKeyPair(keyPair);
        return converter;
    }

}



